//
//  LoginPassWordViewController.m
//  DongFeng_Online-Banking-APP
//
//  Created by wxt on 2021/4/1.
//

#import "LoginPassWordViewController.h"
#import "PassWordViewController.h"
#import <LocalAuthentication/LocalAuthentication.h>
#import "FaceIDViewController.h"
#import "LZActionSheetView.h"
#import "BiomerLognViewController.h"
#import "CodeViewController.h"
#import "HomeViewController.h"

@interface LoginPassWordViewController ()<UITextFieldDelegate,NoNetworkViewDelegate>
@property(nonatomic,strong)TKLtextFiled * passWordF;
@property(nonatomic,strong)TKLlable * messageLab;
@property(nonatomic,strong)UIView * messageView;
@property (retain,nonatomic) LAContext *faceIDContext;
@property (assign,nonatomic) NSInteger BiometryTypeNumber;
@property (strong,nonatomic) NSString * BiometryTypeStr;
@property (nonatomic, strong) UIView *headView;
@property(nonatomic,strong)NSString *authorizationCode;
@property(nonatomic,strong)NSString *authorizationKey;
@property(nonatomic,strong)UIButton * isHiddenBtn;

@property(nonatomic,strong)MBProgressHUD *hud;
@end

static SignMode mode = SignModeRaw;
static IMHashType hashType = IMHashTypeSM3;

@implementation LoginPassWordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self loadUIView];
    [self  isSupportBiometrics];

    
    // Do any additional setup after loading the view.
}
-(void)loadUIView{
    
    UIButton * backBtn =[UIButton createBtnFrame:CGRectMake(15, kStatusBarHeight+5, 18, 18) title:@"" bgImageName:@"fanhui" action:^(UIButton *button) {
        
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    [self.view addSubview:backBtn];
    TKLlable * lognLab = [TKLlable labelWithFrame:CGRectMake(30, 100, 50, 30) text:@"登录" textColor:JhColor(51, 51, 51) font:Font_6(24) textAlignment:Textleft backgroundColor:Ccolor];
    
    lognLab.font = [UIFont fontWithName:@"Arial-BoldMT" size:24];

    [self.view addSubview:lognLab];
    
    
    
    
    UIButton * changeBtn = [UIButton createBtnFrame:CGRectMake(kWidth-120, 110, 100, 20) title:@"更改登录方式" bgImageName:@"" action:^(UIButton *button) {
        [self.view endEditing:YES];
        NSString *biomerStr = [NSString stringWithFormat:@"%@登录",self.BiometryTypeStr];
        NSArray *array = @[biomerStr];
        LZActionSheetView *action = [[LZActionSheetView alloc] initWithTitleView:self.headView optionsArr: array cancelTitle:@"取消" cancelBlock:^{
            
        } selectBlock:^(NSInteger index) {
            
            if (index == 0) {
                
                
                if (self.BiometryTypeNumber == 0) {
                    [MBProgressHUD showError:@"设备暂未开启该权限,请前往设置开启" toView:self.view];
                }else{
                    
                    //生物登录
                    BiomerLognViewController * faceVC = [[BiomerLognViewController alloc]init];
                    
                    faceVC.modalPresentationStyle = 0;
                    faceVC.BiometryTypeStr = self.BiometryTypeStr;
                    faceVC.BiometryTypeNumber = self.BiometryTypeNumber;
                    faceVC.userName = self.userName;
                    faceVC.cerDn = self.cerDN;
                    [self presentViewController:faceVC animated:YES completion:nil];
                }
                
              
            }
            
        }];
        [self.view addSubview:action];
        
    }];
    
  
    
  
    [changeBtn setTitleColor:JhColor(160,160, 160) forState:UIControlStateNormal];
    
    [self.view addSubview:changeBtn];
    //提示信息
    self.messageLab = [TKLlable labelWithFrame:CGRectMake(30, CGRectGetMaxY(lognLab.frame)+30, kWidth-60, 14) text:@"" textColor:[UIColor redColor] font:Font_6(12) textAlignment:Textleft backgroundColor:Ccolor];
    self.messageLab.hidden = YES;
    [self.view addSubview:self.messageLab];
    
    
    
    self.passWordF = [TKLtextFiled FiledWithFrame:CGRectMake(30, CGRectGetMaxY(lognLab.frame)+50,kWidth-120 , 20) text:@"请输入登录密码" textColor:JhColor(51, 51, 51) font:Font_6(14) textAlignment:Textleft backgroundColor:Ccolor];
    [self.passWordF addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    self.passWordF.delegate = self;
        self.passWordF.keyboardType = UIKeyboardTypeDefault ;
    self.passWordF.secureTextEntry = YES;
    
//
    [self.view addSubview:self.passWordF];
    
    
    //密文切换
    
    self.isHiddenBtn = [UIButton createBtnFrame:CGRectMake(CGRectGetMaxX(self.passWordF.frame)+30, CGRectGetMaxY(lognLab.frame)+50, 30, 20) title:@"" bgImageName:@"yincang" action:^(UIButton *button) {
        [self.view endEditing:YES];
        
        [self ishiddenAction];
        
    }];
    
    self.isHiddenBtn.selected = NO;
//    [self.isHiddenBtn setTitleColor:Bcolor forState:UIControlStateNormal];
    [self.view addSubview:self.isHiddenBtn];
    
    
    
    self.messageView = [[UIView alloc]initWithFrame:CGRectMake(30, CGRectGetMaxY(self.passWordF.frame)+10, kWidth-60, 1)];
    self.messageView.backgroundColor = JhColor(153, 153, 153);
    [self.view addSubview:self.messageView];
    
    //next
    UIButton * nextBtn = [UIButton createBtnFrame:CGRectMake(30, CGRectGetMaxY(self.messageView.frame)+20, kWidth-60, 44) title:@"登录" bgImageName:@"" action:^(UIButton *button) {
        [self.view endEditing:YES];

        [self getKey];

        
    }];
//    nextBtn
    nextBtn.backgroundColor = JhColor(21, 126, 251);
    nextBtn.layer.masksToBounds = YES;
    nextBtn.layer.cornerRadius = 5;
    [self.view addSubview:nextBtn];
    
    
    //
  //忘记密码
    UIButton * forgetBtn =[UIButton createBtnFrame:CGRectMake(kWidth-120, CGRectGetMaxY(nextBtn.frame)+10, 100, 20) title:@"忘记密码？" bgImageName:@"" action:^(UIButton *button) {
        [self.view endEditing:YES];
         CodeViewController* codeVC = [[CodeViewController alloc]init];
        codeVC.pushPath = @"oldForget";
        codeVC.phoneNumberStr = self.userPhone;
        codeVC.userName = self.userName;
        codeVC.modalPresentationStyle = 0;
        
        [self presentViewController:codeVC animated:YES completion:nil];
    }];
    [forgetBtn setTitleColor:JhColor(0, 122, 255) forState:UIControlStateNormal];
    [self.view addSubview:forgetBtn];
 
    
}
- (void)textFieldDidChange:(UITextField *)textField{
   
    if (textField == self.passWordF) {
        if (textField.text.length > 16) {
            self.passWordF.text = [textField.text substringToIndex:16];
        }
    }

}
-(void)textFieldDidBeginEditing:(UITextField *)textField{
  
    if (textField == self.passWordF) {
       
        self.messageLab.hidden = YES;
     
    }
    
}
-(void)ishiddenAction{
    
    
    if (self.isHiddenBtn.selected == NO) {
        self.isHiddenBtn.selected = YES;
        [self.isHiddenBtn setBackgroundImage:[UIImage imageNamed:@"xianshi"] forState:UIControlStateNormal];
    }else{
        self.isHiddenBtn.selected = NO;
        [self.isHiddenBtn setBackgroundImage:[UIImage imageNamed:@"yincang"] forState:UIControlStateNormal];
    }
    // 取反

    self.passWordF.secureTextEntry = !self.passWordF.secureTextEntry;
 
// 获得输入的值

    NSString *content = self.passWordF.text;
  
 // 解决输入框从密文切换明文时出现空格的问题

    self.passWordF.text = @"";


    self.passWordF.text = content;

 //如果是密文转明文进行二次编辑不会出现清空现象,如果是明文转密文进行二次编辑就会出现清空现象,进行判断,如果切换后此时输入框是密文状态,就保存原有内容并赋值给输入框,这样就不会出现清空现象了

   if (self.passWordF.secureTextEntry) {

 // 解决输入框从明文切换为密文时进行二次编辑出现清空现象

       [self.passWordF insertText:content];
    

 }

    
}
-(void)isSupportBiometrics{
    
    
    
    self.BiometryTypeNumber = [BiomerTool isSupportBiometrics];

    if (self.BiometryTypeNumber == 1) {
        self.BiometryTypeStr = @"指纹";;
    }else if(self.BiometryTypeNumber == 2){
        
        self.BiometryTypeStr = @"面部";
    }else{
        self.BiometryTypeStr = @"生物";
    }
    

}
-(void)loadUserLoginUrl{
    
  
        
        
        NSString * name = [NSString stringWithFormat:@"%@@@%@",self.userName,self.passWordF.text];
    
        NSString * firstsatr = [TKLTools encryptPassword:name key:self.authorizationCode];
   
        NSString * password = [NSString stringWithFormat:@"%@@@%@",firstsatr,self.authorizationKey];

//签名结果  查询用户本地证书的pin
    
    

    FMDatabase *database =  [DataBaseTool openDataBase];
    
    NSString *selectSql = [NSString stringWithFormat:@"select * from userCer where userName = '%@'",self.userName];

    FMResultSet *resultSet = [database executeQuery:selectSql];
    
    while ([resultSet next]) {

        NSString *payPassord  = [resultSet stringForColumn:@"payWord"];

        IMUser * user = [IMUser userWithUserName:self.userName];

        [user.cert signWithPIN:payPassord Plain:[NSString stringWithFormat:@"%@+%@",self.userName,self.cerDN] encoding:NSUTF8StringEncoding hashType:IMHashTypeSM3 mode:mode andCompleteBlock:^(int resultCode, NSString *signResult) {
            {
                if (resultCode == IM_ER_SUCCESS) {
//                    NSLog(@"%@",self.cerDN);
                    if (signResult != nil) {
        
                        NSDictionary * dic =@{@"grantType":@"password",@"password":password,@"username":self.userName,@"certDn":self.cerDN,@"sign":signResult};
                        NSLog(@"%@",dic);
                        [self loginWithDic:dic];
                        
                    }
                }else{
                    self.hud.hidden = YES;
                    
//                    NSString *errorMsg = [IMError getMsgWithErr:resultCode];
//                    if(resultCode == IM_ER_USER_HAS_BEEN_LOCKED){
//
//                        [self.navigationController popViewControllerAnimated:NO];
//                    }else{
//
//                        NSLog(@"%@",errorMsg);
//                    }
                }
            }
        }];
        
        
        
        
        
     
    }
    [database close];
    


   
    }
    

-(void)loginWithDic:(NSDictionary *)dic{
    NSLog(@"%@",dic);
    [AFNetworkUtils POST_Raw:kUser_Login_Api body:dic.yy_modelToJSONString head:nil success:^(NSDictionary * _Nonnull responseObject) {



         NSLog(@"%@",responseObject);
        
        if ([responseObject[@"code"] intValue] ==200) {
            self.hud.hidden = YES;
            NSDictionary * dataDic= responseObject[@"data"];
             NSString * dataStr = dataDic[@"accessToken"];
            NSString *dealString =dataDic[@"tokenType"];
            NSString *resultString = [TKLTools strFirstBig:dealString];
              
            
            
            
            
            dataStr = [NSString stringWithFormat:@"%@ %@",resultString,dataStr];
    
             NSUserDefaults * stand = [NSUserDefaults standardUserDefaults];
             
             [stand setObject:dataStr forKey:@"token"];
   
             
             NSDictionary * dic = [TKLTools jwtDecodeWithJwtString:dataStr];
     //
             NSString * jsonStr = dic[@"user_name"];

             NSDictionary * jsonDic = [TKLTools dictionaryWithJsonString:jsonStr];
          

             NSString * isChangePass = jsonDic[@"firstEnter"];
            
            [stand setObject:self.userName forKey:@"userName"];
            [stand setObject:self.passWordF.text forKey:@"passWord"];
//                 cs016   1

            [self insterDataList];
             //是否修改过密码  1和 2  均未修改
            self.hud.hidden = YES;
             if ([isChangePass intValue] == 1 || [isChangePass intValue] ==2) {
                 PassWordViewController * passVC = [[PassWordViewController alloc]init];
                 passVC.pushPath = @"newUser";
                 passVC.verifyCode = @"";
                 passVC.userName = self.userName;
                 passVC.phoneNumber = self.userPhone;
                 passVC.modalPresentationStyle = 0;
                 passVC.verifyCode = @"";
                 [self presentViewController:passVC animated:YES completion:nil];
     
     
     
             }else{
                 HomeViewController * tab = [[HomeViewController alloc]init];
                 
                 tab.modalPresentationStyle = 0;
                 [self presentViewController:tab animated:YES completion:nil];
                 
             }

  
        }else{
            
            self.hud.hidden = YES;
            [MBProgressHUD showError:responseObject[@"msg"] toView:self.view];

            
        }


        } failure:^(NSString * _Nonnull error) {
          
        }];
}

-(void)getKey{
    
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
      self.hud.labelText = NSLocalizedString(@"请稍等", @"HUD loading title");
    
    [AFNetworkUtils GET:kAuthorizationCode_Api body:nil head:nil success:^(NSDictionary * _Nonnull responseObject) {
           NSLog(@"%@",responseObject);
        if ([responseObject[@"code"]intValue] == 200) {
            self.authorizationCode = responseObject[@"data"][@"authorizationValue"];
            self.authorizationKey = responseObject[@"data"][@"authorizationKey"];
            
        
            
            [self loadUserLoginUrl];
            
        }else{
            self.hud.hidden = YES;
            [MBProgressHUD showError:responseObject[@"msg"] toView:self.view];
        }

        } failure:^(NSString * _Nonnull error) {
            self.hud.hidden =YES;
            NSLog(@"%@",error);
        }];
    
    
   
    
}

//插入本地数据库
-(void)insterDataList{
    
    NSUserDefaults * stand = [NSUserDefaults standardUserDefaults];
    FMDatabase *database =  [DataBaseTool openDataBase];
    NSString *selectSql = [NSString stringWithFormat:@"select * from user where userName =  '%@'",self.userName];
//    NSString *selectSql = [NSString stringWithFormat:@"select * from user where userName = ‘%@'",self.userName];
    
    FMResultSet *resultSet = [database executeQuery:selectSql];

  
    if ( [resultSet next]) {
        ;
    }else{
        NSString *insertSql = [NSString stringWithFormat:@"INSERT INTO 'user' ('userName', 'passWord') VALUES ('%@', '%@')",self.userName,[stand objectForKey:@"passWord"]];
               BOOL result = [database executeUpdate:insertSql];
      if (!result) {
          NSLog(@"插入失败");
      }else{
          NSLog(@"插入成功");
      }
        
    }
    
    [database close];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
